package atguigu2.readwrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @AUTHOR LYF
 * @DATE 2022/2/4
 * @VERSION 1.0
 * @DESC
 * 读写锁示例
 *
 */

class MyCache {
    // 存放资源
    private Map<String,Object> cache = new HashMap<>();

    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    // 写操作
    public void write(String key,Object value){
        try {
            readWriteLock.writeLock().lock();
            System.out.println(Thread.currentThread().getName()+"进行写操作:"+key);
            TimeUnit.MICROSECONDS.sleep(300);
            cache.put(key, value);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName()+"写操作完成:"+key);
            readWriteLock.writeLock().unlock();
        }
    }


    // 读操作
    public void read(String key){
        Object rs = null;
        try {
            readWriteLock.readLock().lock();
            System.out.println(Thread.currentThread().getName()+"进行读操作:"+key);
            TimeUnit.MICROSECONDS.sleep(300);
            rs = cache.get(key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName()+"读操作完成:"+key+"::"+rs);
            readWriteLock.readLock().unlock();
        }
    }
}


public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 0; i < 5; i++) {
            final String key = i+"";
            new Thread(()->{
                myCache.write(key,key+"-val");
            },"WriteThread-"+i).start();
        }
        for (int i = 0; i < 5; i++) {
            final String key = i+"";
            new Thread(()->{
                myCache.read(key);
            },"ReadThread-"+i).start();
        }
    }
}
